<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use app\admin\model\SiftBanner as ModelSiftBanner;

class SiftBanner extends Controller
{
   public function lst(){
       $res = ModelSiftBanner::all();
       $this->assign('sift_banner', $res);
       return view();
   }

   public function add(){
       if(request()->isPost()){
           // 获取表单上传文件 例如上传了001.jpg
           $file = request()->file('file');
           // 移动到框架应用根目录/public/uploads/ 目录下
           $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'.'/'.'sift_banner');
           if($info){
               $filePath = DS .'uploads'.'/'.'sift_banner'.'/'.$info->getSaveName();
               $path = str_replace("\\", "/", $filePath);
               // $count = Db::table('banner')->count();
               $data = [
                   'url' =>  $path,
               ];
               Db::table('lan_sift_banner')->insert($data);
               $this->success('添加图片成功','lst');
           }else{
               echo $file->getError();
           }
       }
       return view();
   }

    //删除操作
    public function delData(){
        $id = input('id');
        $this->delFile($id);
        $res = ModelSiftBanner::destroy($id);
        if ($res>0){
            return ['code' => 1, 'msg' => '轮播图删除成功'];
        }
        else{
            return ['code' => 0, 'msg' => '轮播图删除失败'];
        }
    }

    public function delFile($id){
        $file_th = db('sift_banner')->where('id', $id)->field('url')->find();
        $al_array_new = implode($file_th);
        $file_s = $_SERVER['DOCUMENT_ROOT'].$al_array_new;
        if (file_exists($file_s)){
            @unlink($file_s);
        }
    }
    public function status(){
        $id = input('id');
        $count = db('sift_banner')->where('status', 1)->count();
        $sh = Db::table('lan_sift_banner')->where(['status' => 1, 'id' => $id]) -> find();
        if ($sh){
            if ($count <= 3){
                return \json(['code' => 2 , 'msg' => '达到图片最低显示']);
            }
            \db('sift_banner')->update(['status' => 0 , 'id'=> $id]);
            return \json(['code' => 1 , 'msg' => '状态更改成功']);
        }else{
            if ($count >= 5){
                return \json(['code' => 2 , 'msg' => '达到可显示图片最多数']);
            }
            \db('sift_banner')->update(['status' => 1 , 'id'=> $id]);
            return \json(['code' => 1 , 'msg' => '状态更改成功']);
        }
    }

}
